package com.xyzk.diagnose.httputils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import com.xyzk.diagnose.activity.bluetooth.BluetoothService;
import com.xyzk.diagnose.entity.Cartype;
import com.xyzk.diagnose.tools.Common;
import com.xyzk.diagnose.tools.Commonfunc;
import com.xyzk.diagnose.tools.Communication;

public class HttpRequest {

	Communication m_com = Communication.getInstance();
	private Cartype cartype = Cartype.getInstance();
	/**
	 * 向指定URL发送GET方法的请求
	 * @param url 发送请求的URL
	 * @param param 请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			URL realUrl = new URL(url + "?" + param);
			URLConnection connection = realUrl.openConnection();
			connection.setConnectTimeout(10000);
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			connection.connect();// 建立实际的连接
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	public static String sendGetWD(String url) {
		String result = "";
		BufferedReader in = null;
		try {
			URL realUrl = new URL(url);
			URLConnection connection = realUrl.openConnection();
			connection.setConnectTimeout(10000);
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			connection.connect();// 建立实际的连接
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		}catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 * @param url 发送请求的 URL
	 * @param param 请求参数
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, String param) {
		OutputStream out = null;
		String result = null;
		try {
			URL realUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
			conn.setConnectTimeout(Common.SERVER_MAX_TIME);
			conn.setDoInput(true);
			conn.setDoOutput(true);
			conn.setRequestMethod("POST");
			conn.setUseCaches(false);
			conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
			conn.setRequestProperty("Content-Length",String.valueOf(param.length()));
			out =conn.getOutputStream();
			out.write(param.getBytes());
			out.flush();
			out.close();
			// 发送请求参数
			if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
				// 定义BufferedReader输入流来读取URL的响应
				BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				String line = "";
				while ((line = br.readLine()) != null) {
					result += line.trim();
				}
				return result;
			}
		} catch (Exception e) {
			try {
				if (out != null) {
					out.close();
					result = "time out!";
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			e.printStackTrace();
		}
		return result;
	}

	public static String sendPut(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
			conn.setRequestMethod("PUT");
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Content-Type","application/json");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 PUT 请求出现异常！"+e);
			e.printStackTrace();
		}
		//使用finally块来关闭输出流、输入流
		finally{
			try{
				if(out!=null){
					out.close();
				}
				if(in!=null){
					in.close();
				}
			}
			catch(IOException ex){
				ex.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 向指定 URL 发送POST方法的请求需要安全证书
	 * @param url 发送请求的 URL
	 * @param param 请求参数
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPostWithVerifier(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			SSLContext context = SSLContext.getInstance("TLS");
			context.init(null, new TrustManager[] { new TrustAllManager()}, new SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
			HttpsURLConnection.setDefaultHostnameVerifier(new MyHostnameVerifier());
			URL realUrl = new URL(url);
			HttpsURLConnection conn = (HttpsURLConnection) realUrl.openConnection();
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(5000);
			//设置授权证书
			conn.setHostnameVerifier(new HostnameVerifier() {

				@Override
				public boolean verify(String hostname, SSLSession session) {
					return true;
				}
			});
			conn.setDoOutput(true);
			conn.setDoInput(true);
			//			conn.addRequestProperty("UserName","ChangheMes");
			//			conn.addRequestProperty("Password","SysCarInfo@eastoneauto.com");
			conn.setRequestProperty("Content-Type","application/json");
			conn.setRequestProperty("Content-Length", String.valueOf(param.length()));
			out = new PrintWriter(conn.getOutputStream());
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			result = "网络或服务器异常!";
			e.printStackTrace();
		}finally{
			try{
				if(out != null){
					out.close();
				}
				if(in != null){
					in.close();
				}
			}
			catch(IOException ex){
				ex.printStackTrace();
			}
		}
		if(result.contains("<Error>")){
			result=result.substring(result.indexOf("<Error>")+7,result.indexOf("</Error>"));
		}
		return result;
	}

	private static class MyHostnameVerifier implements HostnameVerifier{
		@Override
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}

	}

	private static class TrustAllManager implements X509TrustManager{
		@Override
		public void checkClientTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
		}
		@Override
		public void checkServerTrusted(X509Certificate[] chain, String authType)

				throws CertificateException {
		}
		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}

	}

	//获取信息
	public  static String getInfoFromMes(String code,String method){
		// 命名空间
		String nameSpace = "http://tempuri.org/";
		// 指定WebService的命名空间和调用的方法名
		SoapObject rpc = new SoapObject(nameSpace ,method);
		rpc.addProperty("vin",code);
		// 生成调用WebService方法的SOAP请求信息,并指定SOAP的版本
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
		envelope.bodyOut = rpc;
		envelope.dotNet = true;
		envelope.setOutputSoapObject(rpc);
		//		HttpTransportSE transport = new HttpTransportSE("http://10.2.14.167:1006/ElecEquipment.asmx");
		String ip =Common.mes_ip;
		if("Get_ECUInfo".equals(method)){
			ip=Common.mes_ip;
		}
		HttpTransportSE transport = new HttpTransportSE(ip,4000);
		try {
			transport.call(null, envelope);
		} catch (Exception e) {
			e.printStackTrace();
		}
		SoapObject object = (SoapObject) envelope.bodyIn;
		if(object==null){
			return "网络异常";
		}
		//anyType{VinCode=LVUDB17B1KB000101; Status=OK; Message=成功; CarType=F01; MaterialCode=C6473R9BTER0001; Ecoscode1=*K09-3605010AC*8000C0008000FFFF/800200008017FFFF*G21703B520*F01R00DLH2/flashdriver.hex*; Ecoscode2=\\10.2.14.167\ECUsoftware\F01R00DLH2/flashdriver.hex; }
		String result=object.getProperty(0).toString();
		BluetoothService.getInstance().mLog.printMessage(result);
		if(result==null){
			return "数据异常";
		}
		return result;
	}
	//获取信息
	public  static String getcheryVersionFromMes(String Url,String method){
		// 命名空间
		String nameSpace = "http://tempuri.org/";
		// 指定WebService的命名空间和调用的方法名
		SoapObject rpc = new SoapObject(nameSpace ,method);
		//rpc.addProperty("byProvinceName","广东");
		// 生成调用WebService方法的SOAP请求信息,并指定SOAP的版本
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
		envelope.setOutputSoapObject(rpc);
		envelope.dotNet = true;
		envelope.setOutputSoapObject(rpc);
		//String ip = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx";

		HttpTransportSE transport = new HttpTransportSE(Url,4000);
		try {
			transport.call(null, envelope);
		} catch (Exception e) {
			e.printStackTrace();
			BluetoothService.getInstance().mLog.printMessage(e.toString());
		}
		String object = null;
		try {
			object = (String)envelope.getResponse();
		} catch (SoapFault e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		BluetoothService.getInstance().mLog.printMessage("Version:" + object);
		if(object==null){
			return "数据异常";
		}
		return object;
	}
	//上传OBD信息
	public  static String uploadOBDToMes(String param){
//		BluetoothAdapterService.getInstance().m_log.PrintAppend(param);
		// 指定WebService的命名空间和调用的方法名
		//BluetoothService.getInstance().mLog.printMessage(param + "\r\n");
		SoapObject rpc = new SoapObject("http://tempuri.org/","Get_ExhaustInfo");
		rpc.addProperty("str_xml",param);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER12);
		envelope.bodyOut = rpc;
		envelope.dotNet = true;
		envelope.setOutputSoapObject(rpc);
		HttpTransportSE transport = new HttpTransportSE(Common.mes_obd,4000);
		try {
			transport.call(null, envelope);
		} catch (Exception e) {
			e.printStackTrace();
		}
		SoapObject object = (SoapObject) envelope.bodyIn;
		if(object==null){
			return "网络异常";
		}
		String result=object.getProperty(0).toString();
		//BluetoothService.getInstance().mLog.printMessage(result);
		return result;
	}
	public static String sendRequestWithHttpURLConnection(String Pvin,String Purl)
	{
		String resultData = "";
		try {
			// 调用带参数的WebMethod
			//final String SERVER_URL = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName"; // 带参数的WebMethod
			HttpURLConnection conn = null;
			InputStream is = null;
			String param="VIN="+URLEncoder.encode(Pvin,"UTF-8");
			URL url = new URL(Purl); //URL对
			conn = (HttpURLConnection)url.openConnection(); //使用URL打开一个链接,下面设置这个连接
			conn.setRequestMethod("POST"); //使用POST请求
			//参数字符串
			conn.setConnectTimeout(5000);
			DataOutputStream dos=new DataOutputStream(conn.getOutputStream());
			dos.writeBytes(param);
			dos.flush();
			dos.close();

			// 解析返回的内容
			int code = conn.getResponseCode();
			//BluetoothService.getInstance().mLog.printMessage("getResponseCode:" + code);
			if (code == 200) // StatusCode为200表示与服务端连接成功
			{
				is = conn.getInputStream();   //获取输入流
				InputStreamReader isr = new InputStreamReader(is);
				BufferedReader bufferReader = new BufferedReader(isr);
				String inputLine = "";
				while ((inputLine = bufferReader.readLine()) != null) {
					resultData += inputLine + "\n";
				}
				//BluetoothService.getInstance().mLog.printMessage(resultData);
				return resultData;
			}
		} catch (Exception e) {
			e.printStackTrace();
			BluetoothService.getInstance().mLog.printMessage("Error:" + e.toString());
			return null;
		}
		return resultData;

	}

	public static String sendRequestPost(String Purl,String Pdata)
	{
		String resultData = "";
		try {
			URL url = new URL(Purl);
			HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
			httpURLConnection.setConnectTimeout(3000);		//设置连接超时时间
			httpURLConnection.setDoInput(true);                  //打开输入流，以便从服务器获取数据
			httpURLConnection.setDoOutput(true);                 //打开输出流，以便向服务器提交数据
			httpURLConnection.setRequestMethod("POST");			//设置以Post方式提交数据
			httpURLConnection.setUseCaches(false);               //使用Post方式不能使用缓存
			//设置请求体的类型是文本类型
			httpURLConnection.setRequestProperty("Content-Type", "application/json");
			//设置请求体的长度
			httpURLConnection.setRequestProperty("Content-Length", String.valueOf(Pdata.length()));
			//获得输出流，向服务器写入数据
			OutputStream outputStream = httpURLConnection.getOutputStream();
			outputStream.write(Pdata.getBytes());

			int response = httpURLConnection.getResponseCode();            //获得服务器的响应码
			if(response == HttpURLConnection.HTTP_OK) {
				InputStream inptStream = httpURLConnection.getInputStream();
				if(inptStream != null)
				{
					InputStreamReader isr = new InputStreamReader(inptStream);
					BufferedReader bufferReader = new BufferedReader(isr);
					String inputLine = "";
					while ((inputLine = bufferReader.readLine()) != null) {
						resultData += inputLine + "\n";
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return resultData;

	}

	public static String sendPostToMyMes(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			URLConnection conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("Content-Type", "application/json");
			conn.setRequestProperty("user-agent","ApiPOST Runtime +https://www.apipost.cn");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！"+e);
			e.printStackTrace();
		}
		//使用finally块来关闭输出流、输入流
		finally{
			try{
				if(out!=null){
					out.close();
				}
				if(in!=null){
					in.close();
				}
			}
			catch(IOException ex){
				ex.printStackTrace();
			}
		}
		return result;
	}
	public static String sendGetToESPMes(String url, String param) {
		String result="";
		String queryvin="vin="+ param;
		String res = null;
		for (int i = 0; i < 3; i++) {
			//Communication.getInstance().m_log.PrintAppend("test " + i);
			res = HttpRequest.sendGet(url, queryvin); //查询pin码
			System.out.println(res);
			if (res!= null && res.length() > 10) {
				break;
			}
		}
		return result;
	}

	//获取胎压信息服务
	private boolean GetTpmsfromWebservice(){
		byte [] tpmsid = new byte[16];
		if(!Arrays.equals(tpmsid, cartype.tpms)){//不是0000,PIN码已获取，不需要再获取了
			return true;
		}

		boolean result_isok=false;
		String queryvin="resultVin="+new String(cartype.vin);
		String querypin = null;
		for (int i = 0; i < 3; i++) {
			querypin = HttpRequest.sendGet(Common.web_GetTPMS, queryvin); //查询pin码
			System.out.println(querypin);
			if (querypin.indexOf("200") > 0) {
				break;
			}
		}
		if (!querypin.isEmpty()&&querypin.indexOf("200") > 0) {
			try {
				JSONObject jsonObject = new JSONObject(querypin);
				JSONObject result = jsonObject.getJSONObject("data");
				//获取返回的pin码
				// TODO
				byte [] v_id = new byte[4];
				Commonfunc.StringToBytes(result.getString("flId"), v_id,4);
				System.arraycopy(v_id,0,cartype.tpms,0,4);
				Commonfunc.StringToBytes(result.getString("frId"), v_id,4);
				System.arraycopy(v_id,0,cartype.tpms,4,4);
				Commonfunc.StringToBytes(result.getString("rlId"), v_id,4);
				System.arraycopy(v_id,0,cartype.tpms,8,4);
				Commonfunc.StringToBytes(result.getString("rrId"), v_id,4);
				System.arraycopy(v_id,0,cartype.tpms,12,4);
				m_com.m_log.PrintAppend("flid:" + result.getString("flId") + " " +
						"frId:" + result.getString("frId") + " " +
						"rlId:" + result.getString("rlId") + " " +
						"rrId:" + result.getString("rrId"));
				result_isok=true;
			} catch (JSONException e) {
				System.out.println("----获取pin码异常-----"+e);
				e.printStackTrace();
				result_isok=false;
			}
		}else {
			result_isok=false;
		}

		return result_isok;
	}
}
